<!--
 * @Author: fcli
 * @Date: 2023-09-04 10:34:58
 * @LastEditors: fcli
 * @LastEditTime: 2024-05-07 10:18:14
 * @FilePath: /countdown/src/plugin/index.vue
 * @Description: 倒计时组件
-->

<template>
    <div class="count-down">
        <div class="show-time">{{ dateTime }}</div>
        <div class="show-time">{{ dayTime }}</div>
        <div class="show-time">{{ hourTime }}</div>

    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration'
dayjs.extend(duration)
const dateTime = ref('');
const dayTime = ref('');
const hourTime = ref('');

const targetTime = ref('2024-07-01 00:00:00');
let timer = null;
timer && clearInterval(timer);
timer = setInterval(() => {
    showDateTime();
    showDayTime();
    showHourTime();
}, 1);

//展示年、月、日、时、分、秒
const showDateTime = () => {
    const diff = dayjs.duration(dayjs(targetTime.value).diff(dayjs()))
    const year = diff.years() || '';
    const month = diff.months() || '';
    const day = diff.days() || '';
    const hour = diff.hours() || '';
    const minute = diff.minutes() || '';
    const second = diff.seconds() || '';
    // const mill = diff.milliseconds() || '';
    let tempArr = [];
    year && tempArr.push(year + '年');
    month && tempArr.push(month + '月');
    day && tempArr.push(day + '日');
    hour && tempArr.push(hour + '时');
    minute && tempArr.push(minute + '分');
    second && tempArr.push(second + '秒');
    //  mill && tempArr.push(mill);
    dateTime.value = tempArr.join('')
}

//展示日、时、分、秒
const showDayTime = () => {
    const diff = dayjs.duration(dayjs(targetTime.value).diff(dayjs()))
    const day = diff.asDays().toString().split('.')[0];
    const hour = diff.hours() || '';
    const minute = diff.minutes() || '';
    const second = diff.seconds() || '';
    // const mill = diff.milliseconds() || '';
    let tempArr = [];
    day && tempArr.push(day + '日');
    hour && tempArr.push(hour + '时');
    minute && tempArr.push(minute + '分');
    second && tempArr.push(second + '秒');
    // mill && tempArr.push(mill);
    dayTime.value = tempArr.join('')
}
//展示时、分、秒
const showHourTime = () => {
    const diff = dayjs.duration(dayjs(targetTime.value).diff(dayjs()))
    const hour = diff.asHours().toString().split('.')[0];
    const minute = diff.minutes() || '';
    const second = diff.seconds() || '';
    // const mill = diff.milliseconds() || '';
    let tempArr = [];
    hour && tempArr.push(hour + '时');
    minute && tempArr.push(minute + '分');
    second && tempArr.push(second + '秒');
    // mill && tempArr.push(mill);
    hourTime.value = tempArr.join('')
}
</script>
<style>
.show-time {
    font-size: 32px;
}

.count-down {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    flex-direction: column;
}
</style>
